<template>
  <div class="flex flex-col h-full">
    <vxe-card class="w-full" :border="false">
      <AuForm
        ref="formRef"
        :formList="formList"
        :exportBtnFlag="false"
        @submit="search"
      />
    </vxe-card>

    <AuTable
      ref="tableRef"
      v-bind="gridOption"
      class="mt-[16px]"
      @actionClick="actionClick"
    >
      <template #topWrap>
        <div class="text-[#242930]">
          <span class="text-[--autata-font-gray-color]"
            >{{ t("formula_detail.ratio_list") }}：</span
          >
          {{ route.query.name }}
        </div>
      </template>
      <template #status_default="{ row }">
        <el-tag :type="row.publishStatus ? 'success' : 'info'">
          {{
            row.publishStatus
              ? t("formula_detail.status_up")
              : t("formula_detail.status_down")
          }}
        </el-tag>
      </template>
    </AuTable>
    <FormulaDetailModal
      v-model="showDetailModal"
      :rowData="rowData"
      :versionId="versionId"
      @confirm="handleConfirm"
    />
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance, onMounted, reactive, ref } from "vue";
import { AuForm } from "@/components/AuForm";
import { AuTable } from "@/components/AuTable";
import { ACTION_TYPE, PropDefines } from "@/components/AuTable/type";
import {
  tpmFormulaDel,
  TpmFormulaListProp,
  tpmFormulaGetList,
  tpmFormulaPublish
} from "@/api/teaPowder/formula";

import FormulaDetailModal from "./DetailModal.vue";
import { GetListParamProp } from "@/api/user";
import { ElMessage } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import { useGlobal } from "@pureadmin/utils";

import { useI18n } from "vue-i18n";
import { FormulaListProp } from "@/api/teaInfuser/formula";

const { t } = useI18n();
defineOptions({
  name: "FormulaTeaPowderDetail"
});

const emit = defineEmits(["update:showModal"]);
const { proxy } = getCurrentInstance();

// region 页面及组件变量集合
const { $storage } = useGlobal<GlobalPropertiesApi>();
const router = useRouter();
const route = useRoute();

const showUploadModal = ref(false);

const formList = ref([
  {
    type: "input",
    key: "name",
    label: "formula_detail.name",
    labelWidth: "40px",
    placeholder: "formula_detail.name_placeholder"
  },
  {
    type: "select",
    key: "publishStatus",
    label: "formula_detail.status",
    placeholder: "formula_detail.status_placeholder",
    labelKey: "label",
    valueKey: "value",
    emptyValues: [null, undefined],
    options: [
      {
        value: "",
        label: "formula_detail.status_all"
      },
      {
        value: "0",
        label: "formula_detail.status_down"
      },
      {
        value: "1",
        label: "formula_detail.status_up"
      }
    ],
    defaultValue: ""
  }
]);

const showDetailModal = ref(false);
const gridOption = reactive<PropDefines>({
  isServerPage: true,
  showCheckbox: true,
  columns: [
    { field: "formulaId", title: "formula_detail.formula_id" },
    { field: "name", title: "formula_detail.material_name" },
    {
      field: "publishStatus",
      title: "formula_detail.status",
      slots: { default: "status_default" }
    },
    { field: "updateTime", title: "formula_detail.update_time", width: 190 }
  ],
  actions: [ACTION_TYPE.TADD, ACTION_TYPE.EDIT, ACTION_TYPE.TDELETE],
  operateTools: [
    {
      name: "table.putaway",
      key: "putaway",
      seq: 11,
      hiddenHandle: (row: FormulaListProp) => {
        return row.publishStatus === 1;
      }
    },
    {
      name: "table.soldOut",
      key: "soldOut",
      seq: 12,
      hiddenHandle: (row: FormulaListProp) => {
        return row.publishStatus === 0;
      }
    }
  ],
  dataSource: [],
  fetchConfig: {
    query: {
      service: (
        params: GetListParamProp<{ version: string; filter: object }>
      ) => {
        const { start_page, size, ...rest } = params;
        params = {
          start_page: start_page ?? 1,
          size: size ?? 0,
          filter: rest
        };

        return tpmFormulaGetList(params);
      },
      param: () => {
        return {
          version: Number(route.query["id"]),
          ...formRef.value.getFormData()
        };
      }
    }
  }
});
const rowData = ref({});
const versionId = ref(route.query["id"] as string);

const formRef = ref();
const tableRef = ref();
// endregion

// region 页面公共方法集合

const multiDelete = () => {
  if (!tableRef.value.getCheckboxRecords().length) {
    ElMessage({
      message: t("formula_detail.select_delete"),
      type: "warning"
    });
    return;
  }
  proxy.$auMessageBox
    .confirm(t("formula_detail.delete_confirm"), t("notice.title"), {
      type: "error"
    })
    .then(() => {
      const ids = tableRef.value
        .getCheckboxRecords()
        .map((v: TpmFormulaListProp) => v.id);
      tpmFormulaDel({ ids }).then(res => {
        ElMessage({
          message: t("notice.delete_success"),
          type: "success"
        });
        tableRef.value.refresh();
      });
    });
};
// endregion

// region 页面及组件事件集合
const toPrevPage = () => {
  router.go(-1);
};

const search = () => {
  // console.log(data);
  tableRef.value.refresh();
};

const actionClick = ({
  key,
  row
}: {
  key: ACTION_TYPE | string;
  row: TpmFormulaListProp;
}) => {
  switch (key) {
    case ACTION_TYPE.TADD:
    case ACTION_TYPE.EDIT:
      rowData.value = row;
      showDetailModal.value = true;
      break;
    case ACTION_TYPE.TDELETE:
      multiDelete();
      break;
    case "putaway":
    case "soldOut":
      proxy.$auMessageBox
        .confirm(
          t("formula_detail.status_change_confirm", {
            status:
              key === "putaway"
                ? t("formula_detail.status_up")
                : t("formula_detail.status_down"),
            name: row.name
          }),
          t("notice.title"),
          {
            type: "warning"
          }
        )
        .then(() => {
          tpmFormulaPublish({
            ids: [row.id],
            publishStatus: key === "putaway" ? 1 : 0
          }).then(res => {
            if (res.code === 200) {
              ElMessage({
                message: t("notice.operation_success"),
                type: "success"
              });
              tableRef.value.refresh();
            }
          });
        });
      break;
    case ACTION_TYPE.UPLOAD:
      showUploadModal.value = true;
      break;
    case ACTION_TYPE.DOWNLOAD:
      break;
    default:
      break;
  }
};

const handleConfirm = () => {
  tableRef.value.refresh();
};

//导入
const handleUploadConfirm = () => {
  console.log("开始配方导入");
  showUploadModal.value = false;
  tableRef.value.refresh();
};

// endregion

// onMounted(() => {
//   storageConfigureChange("hideTabs", true);
//   emitter.emit("tagViewsChange", true as unknown as string);
// });
//
// onBeforeRouteLeave((to, from, next) => {
//   storageConfigureChange("hideTabs", false);
//   emitter.emit("tagViewsChange", false as unknown as string);
//
//   next();
// });
</script>
